"use client";

import React, { useState, useEffect } from "react";
import { Table } from "antd";
import type { TableColumnsType, TableProps } from "antd";
import type { ResizeCallbackData } from "react-resizable";
import ResizableTitle from "./ResizableTitle";

const ResizeTable: React.FC<TableProps> = (props: TableProps) => {

    const { columns } = props;

    if (!columns?.length) {
        return null;
    }

    const [realColumns, setColumns] = useState<any[]>(columns);

    useEffect(() => {
        setColumns(columns);
    }, [columns]);

    const handleResize =
        (index: number) =>
        (_: React.SyntheticEvent<Element>, { size }: ResizeCallbackData) => {
            const newColumns = [...realColumns];
            newColumns[index] = {
                ...newColumns[index],
                width: size.width,
            };
            setColumns(newColumns);
        };

    const mergedColumns = realColumns.map<TableColumnsType<any>[number]>(
        (col, index) => ({
            ...col,
            onHeaderCell: (column: TableColumnsType<any>[number]) => ({
                width: column.width,
                onResize: handleResize(index) as React.ReactEventHandler<any>,
            }),
        })
    );

    return (
        <Table
            {...props}
            components={{ header: { cell: ResizableTitle } }}
            columns={mergedColumns}
        />
    );
};

export default ResizeTable;
